package com.ls.lserp.modules.setting.web;


import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import freemarker.template.Template;
import groovy.util.ResourceException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.drew.lang.StringUtil;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.setting.entity.InventoryWarning;
import com.ls.lserp.modules.setting.service.InventoryWarningService;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;


/**
  * @ClassName: InventoryWarningController
  * @Description: 
  * 
  * @author 
  * @date 2017年2月27日 上午10:11:26
  */

@Controller
@RequestMapping(value = "${adminPath}/inventory/warning")
public class InventoryWarningController extends BaseController {
	// 保存 编辑 删除 方法
	@Autowired
	private InventoryWarningService inventoryWarningService;
	
	 @Autowired
	Configuration freemarkerConfiguration;

	private Material material;
	 
	/**
	  * @Title: get
	  * @Description: 库存报警
	  * @param @param id
	  * @param @return
	  * @return InventoryWarning 
	  * @throws
	  */
	
	@ModelAttribute
	public InventoryWarning get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return inventoryWarningService.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new InventoryWarning();
		}
	}
	
	/**
	 * 画面跳转用
	 * @param inventoryWarning
	 * @param model
	 * @return
	 */
	
	@RequiresPermissions("inventory:warning:view")
	@RequestMapping(value = { "" })
	public String list(InventoryWarning inventoryWarning, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {
		// 
		model.addAttribute("inventoryWarning", inventoryWarning);
		// 返回页面地址
	    return "modules/setting/inventoryWarning";
	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面 
	 */
	
	@RequiresPermissions("inventory:warning:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(InventoryWarning inventoryWarning, HttpServletRequest request, HttpServletResponse response, Model model)
			throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();

		
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "inventoryWarning");
	
		// 画面取得的检索项目
		String materialUseType = inventoryWarning.getMaterial().getMaterialUseType();
		String materialTypeCd = inventoryWarning.getMaterial().getMaterialTypeCd();
		String materialNameCn = inventoryWarning.getMaterial().getMaterialNameCn();
		String materialColor = inventoryWarning.getMaterial().getMaterialColor();
		String materialComposition = inventoryWarning.getMaterial().getMaterialComposition();
		
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 拼接字符串供分页使用
		String searchParam ="&materialUseType="+materialUseType+"&materialTypeCd="+materialTypeCd+"&materialNameCn="+materialNameCn+"&materialColor="+materialColor+"&materialComposition="+materialComposition;
		
		// 当选择定制订单时，可以查询全部和定制订单信息
    	if(StringUtils.isNoneBlank(material.getMaterialUseType())){
    		if(material.getMaterialUseType().equals(ResourcesUtil.getConfig("material_customization"))){
    			material.setMaterialUseType(ResourcesUtil.getConfig("material_all")+","+ResourcesUtil.getConfig("material_customization"));
    		}
    	}
    	
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<InventoryWarning> page = inventoryWarningService.findList(new Page<InventoryWarning>(request, response), inventoryWarning);
		
		String strHtml = "";
		
		try{
			Map<String, Object>  map = new HashedMap();
			map.put("adminUri",strUri);
			map.put("inventoryWarnings",page.getList());
			map.put("pageNo",page.getPageNo());
			map.put("pageSize",page.getPageSize());

			strHtml  =	FreeMarkerTemplateUtils.processTemplateIntoString(
				freemarkerConfiguration.getTemplate("inventoryWarning.ftl"), map);
		}
		catch (Exception ex) {
		}
		
		listMap.put("inventoryWarning", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	
	/**
     * @Title: show
     * @Description: 查看库存报警
     * @param @param inventoryWarning
     * @param @param model
     * @param @return
     * @return String 
     * @throws
     */
   
   @RequiresPermissions("inventory:warning:view")
   @RequestMapping(value = "show")
   public String show(InventoryWarning inventoryWarning, Model model) {
   	
   	// 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("inventoryWarning", inventoryWarning);
       
       // 返回页面地址
       return "modules/setting/inventoryWarningShow";
   }
   
	/**
	  * @Title: form
	  * @Description: 新建及编辑
	  * @param @param inventoryWarning
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("inventory:warning:edit")
	@RequestMapping(value = "form")
	public String form(InventoryWarning inventoryWarning,RedirectAttributes redirectAttributes, Model model) {
	    
		if(StringUtils.isBlank(inventoryWarning.getMaterial().getMaterialBarCode())){
			
			inventoryWarning.getMaterial().setMaterialBarCode(SequenceUtil.materialbarcode().getReturnCode());
	    }
		//将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("inventoryWarning", inventoryWarning);
		
		// 返回页面地址
		return "modules/setting/inventoryWarningCreate";
	}
	
	
	/**
     * @Title: delete
     * @Description: 删除库存
     * @param @param inventoryWarning
     * @param @param response
     * @param @return
     * @return String 
     * @throws
     */
   
   @RequiresPermissions("inventory:warning:edit")
	@RequestMapping(value = "delete")
	public String delete(InventoryWarning inventoryWarning, HttpServletResponse response) {
		
		    try {
		    	
		    	// 执行逻辑删除方法
		    	inventoryWarningService.deleteInventory(inventoryWarning);
           } catch (Exception e) {
               // 记录日志
               logger.error(e.getMessage(), e);
           	// 提示错误信息
               return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
           }
		    
		 // 提示删除成功信息
			return renderString(response,AjaxDone.ok(getText("category_delete_success")));
   }
	

		/**
		  * @Title: save
		  * @Description: 保存数据
		  * @param @param inventoryWarning
		  * @param @param request
		  * @param @param model
		  * @param @param response
		  * @param @return
		  * @return String 
		  * @throws
		  */

		@RequiresPermissions("inventory:warning:edit")
		@RequestMapping(value = "save")
		@ResponseBody
		public String save(InventoryWarning inventoryWarning,UploadFile  uploadFile, HttpServletRequest request, Model model, HttpServletResponse response ) {
			
			// 判断id是否为null （判断新建或修改）
			if(inventoryWarning.getId()!=null){
				
				// 编辑数据
				// 判断数据是否删除
				InventoryWarning materialNew=get(inventoryWarning.getId().toString());
	            
				// 判断数据是否删除
				if(materialNew==null || BaseEntity.DEL_FLAG_DELETE.equals(inventoryWarning.getDeleteFlag())){
	                
					// 返回提示信息
					return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	            }
				
			    //排他
			    if(inventoryWarning.getVersion()==get(inventoryWarning.getId().toString()).getVersion()){
			    	
			    	// 版本号加1
			    	inventoryWarning.setVersion(inventoryWarning.getVersion()+1);
			    }else{
			    	
			    	// 返回提示信息
			        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			    }
			}else{
				
				// 新建版本号赋值1
				inventoryWarning.setVersion(1L);
			}
			
			// 保存图片
			if(uploadFile.getFilePath()!=null){
				
	            // 图片来源：1.电脑端 ,2.手机端
				uploadFile.setFileSource(1L);
	            // 所在模块区分（1:需求单 2:款式 3:订单 4:测试 5:工艺图片）
				uploadFile.setModuleKbn(4L);
	            // ftp文件名
				uploadFile.setFtpFile(ResourcesUtil.getConfig("material_picture_url"));
	            
	            // 上传文件路径(以免两个值互相影响)
	            String filePath = uploadFile.getFilePath();
	            // 前台显示路径
	            uploadFile.setShowImgUrl(filePath);
	            // 上传文件路径
	            uploadFile.setFilePath(uploadFile.getFilePath().substring(0,uploadFile.getFilePath().lastIndexOf('/') + 1));
	            // 上传文件
	            uploadFile.setUploadFile(filePath.substring(filePath.lastIndexOf('/') + 1));
	            
	            inventoryWarning.setUploadFile(uploadFile);
			}
			
			
			
			try {
				// 若启用未选择赋值1
				if(inventoryWarning.getEnableFlag()==null){
					inventoryWarning.setEnableFlag("1");
				}
				
			    // 保存库存
				inventoryWarningService.saveInventory(inventoryWarning);
				
				// 保存成功返回提示信息
		        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "materialSaveSuccess")));
			 } catch (Exception e) {
		           // 记录日志
		           logger.error(e.getMessage(), e);
				// 提示错误信息
				return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		     }
		}



}
